package com.scedu.controller;


import lombok.extern.slf4j.Slf4j;


import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${upload.dir}")
    private String uploadPath;//文件上传保存目录

    //文件下载
    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //根据文件名去指定目录中查找文件
        String realPath=uploadPath; //存到配置文件的files目录
        realPath = java.net.URLDecoder.decode(realPath, "utf-8"); //解决Java获取文件路径出现乱码的问题
        //读取文件
        File file=new File(realPath,fileName);
        //获取文件输入流
        FileInputStream inputStream =new FileInputStream(file);
        //以附件形式下载 attachment;附件下载 inline 在线打开（图片 pdf）
        response.setHeader("content-disposition", "attachment;fileName="+fileName);
        //获取响应输出流
        ServletOutputStream outputStream=response.getOutputStream();
        //文件拷贝
//        int len=0;
//        byte[] bytes =new byte[1024];
//        while(true){
//            len=inputStream.read(bytes);
//            if(len==-1){
//                break;
//            }
//            outputStream.write(bytes);
//        }
//        //关流
//        inputStream.close();
//        outputStream.close();
        //文件拷贝新写法
        IOUtils.copy(inputStream,outputStream);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);

    }


    @PostMapping("/fileupload")
    public  String fileupload(MultipartFile aa, HttpServletRequest request) throws IOException { //MultipartFile类型的变量名必须和前端一致
        //接收文件上传
         log.info("原始文件名={}",aa.getOriginalFilename());
         log.info("文件类型={}",aa.getContentType());
         log.info("文件大小={}",aa.getSize());
         //处理文件上传
        String realpath= uploadPath; //存到配置文件的files目录
        // realpath = java.net.URLDecoder.decode(realpath, "utf-8"); //解决Java获取文件路径出现乱码的问题
        log.info("转码后上传文件夹在    {}",realpath);
        //日期目录创建
        String yearDir= new SimpleDateFormat("yyyy/MM").format(new Date());
        File targetDir=new File(realpath,yearDir); //按年月生成文件夹
        if(!targetDir.exists()) {targetDir.mkdirs();} //不存在则创建目录
        //修改文件名 时间戳+UUID
        String newFileName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+UUID.randomUUID().toString();
        String fileExtension= FilenameUtils.getExtension(aa.getOriginalFilename()); //后缀不变
        String newfilename=newFileName+"."+fileExtension;
        aa.transferTo(new File(targetDir,newfilename));
        log.info("上传ok");
        return  "redirect:/upload.html";
    }
}
